
import { createSlice,createAsyncThunk } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import {message as Massage } from 'antd';
import http from "@/src/utils/https";
import { useEffect } from 'react';

interface LoginVal{
    username:string,
    password:string
}


//登录
const  getLogin = (obj:LoginVal)=>{
    return http.post("/login",obj)
 }
//注册
const  setLogin = (obj:LoginVal)=>{
    return http.post("/register",obj)
 }


export interface CounterState {
  user:object,
  token:string
}

const initialState: CounterState = {
  user:{},
  token:"",
}


export const counterSlice = createSlice({
  name: 'login',
  initialState,
  reducers: {
    
  },
  extraReducers: (builder) => {
    builder.addCase(getlogin.fulfilled,(state,{payload})=>{
        if(payload){
          if(payload.message){
            Massage.success(payload.message)
        }
        state.token = payload.token
        localStorage.setItem("token",state.token)
        state.user = {...payload.data}
        localStorage.setItem("user",JSON.stringify(state.user))
        }else{
          Massage.warning("登录失败")
        }
    })
  },
})

//登录
export const getlogin = createAsyncThunk('login/getLogin',async(obj:LoginVal)=>{
    let res = await getLogin(obj)
    // console.log(res , 'res')
    if(res.data.code==200){
        return res.data
    }
})
//注册
export const setlogin = createAsyncThunk('login/setLogin',async(obj:LoginVal)=>{
    let res = await setLogin(obj)
    if(res.data.code==200){
        return res.data
    }
})

export const {  } = counterSlice.actions




export default counterSlice.reducer